/** 滚动浮动*/
import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import { BottomFrameSty, CanvasSty, TopFrameSty } from './style'
import airPodsPro from '@/assets/video/airpods-pro.webm'

export default function Index() {

  const canvasDom = useRef<any>(null)
  const canvasCtx = useRef<any>(null)
  const canvasDomOne = useRef<any>(null)
  const canvasCtxOne = useRef<any>(null)
  const videoDom = useRef<any>(null);
  const videoFrame = useRef<any>(null)

  const [height, setHeight] = useState(0)
  const [width, setWidth] = useState(0)
  const [style, setStyle] = useState({})
  /** 最小滚动距离*/
  const minScroll = useRef(0)
  /** 最大滚动距离*/
  const maxScroll = useRef(0)
  /** 播放时间*/
  const videoTime = useRef(0)
  /** 最近滚动元素*/
  const scrollElement = useRef(null)
  const topDom = useRef(null)


  /** 获取视频时长*/
  const onLoadedmetadata = () => {
    if (videoDom.current === null) {
      return
    }
    const duration = videoDom.current.duration;
    videoTime.current = duration;
  }

  useEffect(() => {
    if (videoFrame.current === null || videoDom.current === null) {
      return
    }

    const onInit = () => {
      if (videoFrame.current === null || topDom.current === null) {
        return
      }
      let info = videoFrame.current.getBoundingClientRect();
      let topDomInfo = (topDom.current as any).getBoundingClientRect();

      minScroll.current = (topDom.current as any).offsetTop + topDomInfo.height;
      maxScroll.current = minScroll.current + info.height;

      setHeight(info.height)
      setWidth(info.width)
      /** 因为Canvas的大小变化时，其内部的绘图上下文也会被重置，可能导致之前绘制的内容丢失
       * 要等待一段时间
      */
      requestAnimationFrame(() => {
        videoDom.current && onScroll()
      })
    }

    /** 滚动时触发*/
    const onScroll = () => {
      let scrollTop = (scrollElement.current as any).scrollTop;

      if (scrollTop >= minScroll.current && scrollTop < maxScroll.current) {
        setStyle({
          position: 'sticky',
        })
      } else {
        setStyle({
          position: 'relative',
        })
      }

      /** 单位速度*/
      let speed = videoTime.current / (height);
      let scrollHeight = scrollTop - (minScroll.current);
      let currentTime = 0;

      if (scrollHeight < 0) {
      } else if (scrollHeight > 0 && scrollHeight < height) {
        currentTime = scrollHeight * speed;
      } else {
        currentTime = videoTime.current;
        videoDom.current.currentTime = currentTime;
        canvasCtxOne.current.drawImage(videoDom.current, 0, 0, width, height);
      }
      videoDom.current.currentTime = currentTime;
      canvasCtx.current.drawImage(videoDom.current, 0, 0, width, height);
    }

    scrollElement.current = (videoFrame.current as any).closest('.scrollElement')
    canvasCtx.current = canvasDom.current.getContext('2d');
    canvasCtxOne.current = canvasDomOne.current.getContext('2d');
    const resizeObserver = new ResizeObserver(entries => {
      onInit()
    });
    resizeObserver.observe(scrollElement.current as any);
    (scrollElement.current as any).addEventListener('scroll', onScroll);
    videoDom.current.addEventListener('loadedmetadata', onLoadedmetadata);

    return () => {
      (scrollElement.current as any).removeEventListener('scroll', onScroll);
      videoDom.current && videoDom.current.removeEventListener('loadedmetadata', onLoadedmetadata);
      resizeObserver.disconnect()
    }
  }, [height, width])

  return (
    <>
      <TopFrameSty ref={topDom} >
        <h1>往下滚动</h1>
      </TopFrameSty>

      <CanvasSty
        ref={videoFrame}
        style={style}
      >
        <canvas ref={canvasDom}
          width={width}
          height={height}
        ></canvas>
      </CanvasSty>

      <BottomFrameSty>
        <canvas ref={canvasDomOne}
          width={width}
          height={height}
        ></canvas>
      </BottomFrameSty>

      <BottomFrameSty />
      <video
        style={{
          display: 'none'
        }}
        ref={videoDom}
        src={airPodsPro}
      ></video>
    </>
  )
}
//其他备用视频链接
//  http://nice.zuo11.com/5-airpods-pro-play-video-on-scroll/airpods-pro.webm
// https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/dancer/small.webm